<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>成本管理</el-breadcrumb-item>
      <el-breadcrumb-item>账单详情</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>promotion detail</el-breadcrumb-item> -->
    </el-breadcrumb>

    <!-- 白色区域内容 -->
    <div class="page_content">
      <div class="flex">
        <div class="input_box">
          <el-input v-model="input3" placeholder="按照账单细节名搜索" class="input-with-select">
            <template #append>
              <el-button @click="searchByName"><i class="el-icon-search"></i><el-icon><Search /></el-icon></el-button>
            </template>
          </el-input>
        </div>

       
        <!-- //添加账单账单细节窗口 -->
        <el-dialog title="添加账单细节信息" v-model="addDialogVisible">
          <el-form :model="addForm" label-position="left" label-width="80px">
             <!-- <el-form-item label="账单分类">
            <el-input v-model="addForm.costtpyeId"></el-input>
            </el-form-item> -->
            <el-form-item label="账单分类">
            <el-select v-model="editForm.costtpyeId" placeholder="请选择分类">
                <el-option
                v-for="item in costTypeList"
                :key="item.id"
                :label="item.costname"
                :value="item.id">
                </el-option>
            </el-select>
            </el-form-item>

            <el-form-item label="描述">
            <el-input v-model="addForm.detail"></el-input>
            </el-form-item>

            <el-form-item label="金额">
            <el-input v-model="addForm.amount" ></el-input>
            </el-form-item>

            <el-form-item label="收款方">
            <el-input v-model="addForm.collect" ></el-input>
            </el-form-item>

            <el-form-item label="备注">
            <el-input v-model="addForm.mark" ></el-input>
            </el-form-item>

            <el-form-item label="时间">
            <el-date-picker v-model="addForm.date" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间"></el-date-picker>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser(addForm)">确 定</el-button>
          </div>
        </el-dialog>

        <div class="flex">
      
        
        <!-- 增加一个删除的按钮 -->
        <el-button type="danger" @click="showDeleteCheckbox=!showDeleteCheckbox">{{ showDeleteCheckbox ? '取消删除' : '删除' }}</el-button>
          <el-button type="button" @click="addDialogVisible = true" class="myButton">新建</el-button>
        </div>
      </div>
      <!-- 显示复选框 -->
      <el-table :data="tableData" stripe style="width: 100%"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="showDeleteCheckbox"></el-table-column>
        <el-table-column prop="id" label="id" width="100" />
        <!-- <el-table-column prop="costtpyeId" label="分类" width="180" /> -->
        <el-table-column prop="costtpyeId" label="分类" width="180">
            <template #default="{ row }">{{ Mymap[row.costtpyeId] }}</template>
        </el-table-column>

        <el-table-column prop="collect" label="收款方" width="180" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="date" label="时间" />
           <el-table-column fixed="right" label="操作" width="180">
          <template #default="{row}">
            <el-button type="button" @click="handleDetail(row)" class="myButton1">详情</el-button>
            <el-button type="button" @click="handleEdit(row)" class="myButton1">编辑</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!-- 删除按钮 -->
      <div style="text-align: center; margin-top: 20px;" v-if="showDeleteCheckbox">
        <el-button type="danger" @click="deleteSelectedRows()">删除所选</el-button>
      </div>
    </div>

    <!-- 编辑窗口 -->
    <el-dialog title="编辑账单细节信息" v-model="editDialogVisible">
       <el-form :model="editForm" label-position="top" label-width="80px">
            <!-- <el-form-item label="账单分类">
            <el-input v-model="editForm.costtpyeId"></el-input>
            </el-form-item> -->
            <el-form-item label="账单分类">
            <el-select v-model="editForm.costtpyeId" placeholder="请选择分类">
                <el-option
                v-for="item in costTypeList"
                :key="item.id"
                :label="item.costname"
                :value="item.id">
                </el-option>
            </el-select>
            </el-form-item>


            <el-form-item label="描述">
            <el-input v-model="editForm.detail"></el-input>
            </el-form-item>

            <el-form-item label="金额">
            <el-input v-model="editForm.amount" ></el-input>
            </el-form-item>

            <el-form-item label="收款方">
            <el-input v-model="editForm.collect" ></el-input>
            </el-form-item>

            <el-form-item label="备注">
            <el-input v-model="editForm.mark" ></el-input>
            </el-form-item>

            <el-form-item label="时间">
            <el-date-picker v-model="editForm.date" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间"></el-date-picker>
            </el-form-item>
        </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button class="myButton1" type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
    <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  </div>
</template>

<script setup>
import { h, onMounted, reactive, ref } from 'vue';
import axios from '../../utils/axios';
import { ElMessageBox, ElMessage, ElDatePicker } from 'element-plus';


let tableData = reactive([]);
const input3 = ref('');
//分页设置
let page = 1;
let size = 5;
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
const total = ref(0)

const editDialogVisible = ref(false);
const addDialogVisible = ref(false);
const editForm = reactive({
  id:'',
  date:'',
  costtpyeId: '',
  detail: '',
  amount: 0.00,
  collect: '',
  mark: ''
});
const addForm = reactive({
    id:'',
    date:'',
    costtpyeId: '',
    detail: '',
    amount: 0.00,
    collect: '',
    mark: '',
    userid: 1
});
const showDeleteCheckbox = ref(false);
let selectedRows = reactive([]);
let seletionIds = reactive([]);

const handleSizeChange = (val) => {
  size = val;
  refreshTableData();
} 
const handleCurrentChange = (val) => {
  page = val;
  refreshTableData();
}

const handleDetail = (row) => {
  ElMessageBox({
    title: '账单详情',
    message: h('div', null, [
      h('p', null, `ID: ${row.id}`),
      h('p', null, `日期:${row.date}`),
      h('p', null, `分类：${row.costtpyeId}`),
      h('p', null, `金额：${row.amount}`),
      h('p', null, `收款方：${row.collect}`),
      h('p', null, `详情：${row.detail}`),
      h('p', null, `备注：${row.mark}`)
    ]),
  });
};


const handleEdit = (row) => {
  // 对editForm进行初始化
  editForm.id = row.id;
  editForm.date = row.date;
  editForm.costtpyeId = row.costtpyeId;
  editForm.detail = row.detail;
  editForm.amount = row.amount;
  editForm.collect = row.collect;
  editForm.mark = row.mark;
  editDialogVisible.value = true;
};


const cancelEdit = () => {
  editDialogVisible.value = false;
  resetEditForm();
};

const submitEdit = () => {
// 将开关的值进行转换
  axios.put('/cost/', editForm).then((res) => {
    console.log('提交修改：', editForm);
    console.log("res为：")
    console.log(res) 
    ElMessage.success('账单细节数据修改成功')
    refreshTableData();
    editDialogVisible.value = false;
  }).catch((err) => {
    console.error(err);
    // 使用element-plus的message组件
    ElMessage.error('提交失败，请稍后再试');
  });
};

const resetEditForm = () => {
  editForm.id = tableData[tableData.length - 1].id + 1;
  editForm.date = '';
  editForm.costtpyeId = '';
  editForm.detail = '';
  editForm.amount = 0.00;
  editForm.collect = '';
 editForm.mark = '';
};

const resetAddForm = () => {
  addForm.id = '';
  addForm.date = '';
  addForm.costtpyeId = '';
  addForm.detail = '';
  addForm.amount = 0.00;
  addForm.collect = '';
  addForm.mark = '';
};

const handleSelectionChange = (value) => {
  selectedRows = reactive([]);
  selectedRows.value = value;
};


//根据名字模糊查询
const searchByName = () => {
  if (!input3.value) {
   refreshTableData();
  } else {
    axios.get(`/cost/search/${input3.value}`).then((res) => {
      console.log('提交查询：', input3.value);
      console.log('res为：', res);
      console.log('res.data:', res.data);
      if (res.code === 200) {
        const result = res.data;
        tableData.splice(0, tableData.length);
        for (let i in result) tableData.push(result[i]);
        console.log(',tableData：', tableData);
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((err) => {
      console.error(err);
      ElMessage.error('获取账单细节列表失败');
    });
  }
};





const deleteSelectedRows = () => {
  const count = selectedRows.value.length;
  if (count > 0) {
    ElMessageBox.confirm(`已选择 ${count} 条数据，是否确认删除？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      const ids = selectedRows.value.map((row) => row.id);
      for (let id of ids) {
        axios.delete('/cost/' + id).then((res) => {
          console.log("删除后的数据如下");
          console.log(res);
          console.log(res.code);
          if (res.code == 200) {
            showDeleteCheckbox.value = false;
            selectedRows.value = [];
            ElMessage.success('删除成功！');
            refreshTableData();
          } else {
            ElMessage.error('删除失败！');
          }
        }).catch((err) => {
          console.error(err);
          ElMessage.error('删除失败，请稍后再试');
        });
      }
    }).catch(() => {
      // do nothing
    });
  }
};


//添加账单账单细节的方法
const addUser = (addForm) => {
  addDialogVisible.value = true;
   console.log("添加账单细节addForm为：",addForm)
  axios.post('/cost/',addForm).then((res) => {

    console.log("添加账单细节res为：")
    console.log(res)
    if (res.code == 200) {
      tableData.push(res.data);
      refreshTableData();
      ElMessage.success("添加账单细节成功");
      resetAddForm();
       addDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('添加账单细节失败');
  });
};

//初始化请求数据
const refreshTableData = () => {
  axios.get(`/cost/list/${page}/${size}`).then((res) => {
    console.log("res为：")
    console.log(res)
    if (res.code == 200) {

      tableData.splice(0, tableData.length);
      total.value = res.data.total
      const result = res.data.list;
      for (let i in result) tableData.push(result[i]);
       console.log("tabl0eData")
      console.log(tableData)
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('获取菜单列表失败');
  });
};

let Mymap = new Map();
const fetchCostTypeList = async () => {
 await axios.get('/cost_type/costnames').then((res) => {
     console.log("costnames为：",res)
     Mymap = res.data
    console.log("Mymap:",Mymap)
 }).catch((err) => {
    console.log(err);
    ElMessage.error('获取分类列表失败');
  });
};

let costTypeList = reactive([]);
const fetchCostName = () => {
 axios.get('/cost_type/list').then((res) => {
     console.log("costnamesOnly",res)
     costTypeList = res.data;
    console.log("costTypeList:",costTypeList)
    console.log("costTypeList:",typeof(costTypeList))
 }).catch((err) => {
    console.log(err);
    ElMessage.error('获取分类列表失败');
  });
};

onMounted(() => {
  refreshTableData();
  fetchCostTypeList();
  fetchCostName();
});

</script>

<style scoped>
.page_content {
  margin: 20px;
  padding: 20px;
  background-color: white;
}

.flex {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  /* margin-right: 5px; */
  padding: 10px;
}

.myButton {
  margin-right: 10px;
  height: 32px;
  line-height: 30px;
  background-color: #5ad2ad;
  border-color: #8ddc88;
  color: white;
  float:right;
}

.myButton1 {
  margin-right: 10px;
  height: 32px;
  line-height: 30px;
  background-color: #70a6e0;
  border-color: #80b4ec;
  color: white;
  float:right;
}
.input_box .el-input {
  width: 250px;
}

.el-button.link {
  color: #8ddc88;
  background-color: transparent;
  border-color: transparent;
}

.dialog-footer {
  text-align: right;
}
</style>